import { useMutation, useQuery } from '@tanstack/react-query';
import { Button, Drawer, Form, Input, message, Modal, Typography } from 'antd';
import { useEffect } from 'react';
import React from 'react';

import api from '@/apis/api';
import localINFO from '@/utils/localInfo';
import LocalInfo from '@/utils/localInfo';

import Circle from '../RateCicle';

const { Text } = Typography;

interface FileSpaceDrawerProps {
  open: boolean;
  setOpen: (open: boolean) => void;
}

const FileSpaceDrawer = ({ open, setOpen }: FileSpaceDrawerProps) => {
  const [totalSpace, setTotalSpace] = React.useState(0);
  const [usedSpace, setUsedSpace] = React.useState(0);
  const [unit, setUnit] = React.useState('MB');

  const [form] = Form.useForm();
  const [visible, setVisible] = React.useState(false);

  // 获取文件空间使用情况
  const { data: FileSpaceData } = useQuery({
    queryKey: ['getFileSpace'],
    queryFn: async () => {
      const res: any = await api.GetFileSpace();
      return res.data;
    },
    enabled: !!open,
  });

  // 初始化空间
  const Initialize = useMutation({
    mutationFn: (params: any) => api.InitializeFileSpace(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        message.success('初始化成功');
      } else {
        message.error(`初始化失败,${res?.message}`);
      }
    },
    onError: () => {
      message.error('初始化失败');
    },
  });

  useEffect(() => {
    if (FileSpaceData) {
      console.log(FileSpaceData, 'FileSpaceData');
      setTotalSpace(FileSpaceData?.total_memory);
      setUsedSpace(FileSpaceData?.local_memory);
      setUnit(FileSpaceData?.unit);
    }
  }, [FileSpaceData]);

  const onInitialize = async () => {
    await form.validateFields();
    const adminPassword = form.getFieldValue('adminPassword');
    Initialize.mutate({
      password: adminPassword,
    });
    setVisible(false);
    form.resetFields();
  };
  const handleInitializeCancel = () => {
    setVisible(false);
    form.resetFields();
  };

  return (
    <>
      <Drawer
        title="文件空间使用情况"
        placement="right"
        width={450}
        onClose={() => setOpen(false)}
        open={open}
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            padding: '20px',
            backgroundColor: '#f5f5f5',
            borderRadius: '8px',
          }}
        >
          <div style={{ flex: 1, textAlign: 'left' }}>
            <div style={{ marginBottom: '10px' }}>
              <Text strong>已使用的文件空间</Text>
              <p style={{ fontSize: '16px', margin: '5px 0' }}>{`${usedSpace}${unit}`}</p>
            </div>
            <div style={{ marginBottom: '20px' }}>
              <Text strong>总文件空间</Text>
              <p
                style={{ fontSize: '16px', margin: '5px 0' }}
              >{`${totalSpace}${unit}`}</p>
            </div>
            <Button
              type="primary"
              onClick={() => setVisible(true)}
              disabled={LocalInfo.getRoleId() === 2}
            >
              空间初始化
            </Button>
          </div>
          <div style={{ flex: 1, textAlign: 'center' }}>
            <Circle
              rate={totalSpace !== 0 ? ((usedSpace / totalSpace) * 100).toFixed(1) : 0}
              title="已使用"
            />
          </div>
        </div>
      </Drawer>
      <Modal
        title="验证管理员密码"
        open={visible}
        onOk={onInitialize}
        onCancel={handleInitializeCancel}
        cancelText="取消"
        okText="确定"
        destroyOnClose
        okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <Form
          form={form}
          preserve={false}
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600, marginTop: 24, marginBottom: 24, width: 450 }}
          autoComplete="off"
        >
          <Form.Item
            label="管理员密码"
            name="adminPassword"
            rules={[{ required: true, message: '请输入管理员密码！' }]}
            style={{ marginBottom: 0 }}
          >
            <Input.Password placeholder="请输入管理员密码" autoComplete="new-password" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default FileSpaceDrawer;
